package com.vincent.kdp.util;

/**
 * Created by fanzhengguang on 2016/11/20.
 */

import java.util.List;

import com.RFID.RFIDReader;
import com.RFID.RFIDReader.*;
import com.RFID.TAGINFO;
import com.vincent.kdp.util.ReaderParams;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class UhfDev extends Object {
    private Handler msgHandler = null;
    public final static int MSG_INFO = 0;
    public final static int MSG_EPC = 1;
    public final static int MSG_STOP = 3;
    public final static int MSG_OPEN = 4;
    public final static int MSG_TIMER = 5; // 定时器
    public final static int MSG_PAUSE = 6;	//暂停
    public final static int MSG_RESUME = 7;	//继续

    private final int DEV_STAT_CLOSE = 0;
    private final int DEV_STAT_OPEN = 1;
    private int devStat = DEV_STAT_CLOSE;
    private final int CMD_CLOSE = 0;	//盘存状态:停止
    private final int CMD_PAUSE = 1;	//盘存状态:暂停
    private final int CMD_INV = 2;			//盘存状态:盘存
    private int devOpt = CMD_PAUSE;	//默认状态：暂停
    public int rReadTime = 100; // 盘存时间：多标签=Rparam.readtime;单标签=100ms;
    public int rSleepTime = 1; // 等待时间
    public RFIDReader reader = null;
    public ReaderParams Rparams = null;
    private boolean runFlag = true;
    private static UhfDev instance= null;
    private Thread thInventory = null; // 盘存线程句柄
    private int m_iModType = 0;	//A8-A模式

    public static synchronized UhfDev getInstance() {
        if (instance == null) {
            instance = new UhfDev();
        }
        return instance;
    }

    public boolean init(int iModType) {
        reader = new RFIDReader();
        if (!reader.Init(iModType)) {
            sendMsg(MSG_INFO, "初始化失败");
            return false;
        }
        m_iModType = iModType;
        Rparams = new ReaderParams();
        return true;
    }

    // region Inventory Thread
    //Start Device Inventory
    public void StartDev(Handler handler) {
        msgHandler = handler;
        devOpt = CMD_PAUSE;

        if(0==m_iModType)
            StartInvThread(); // 启动盘存
    }

    //region 采用单次发送模式: 用于A8-A模式
    // Start Device Inventory
    private void StartInvThread() {
        runFlag = true;
        if (null == thInventory) {
            thInventory = new Thread(sendable);
            thInventory.start();
        }
    }

    //Stop Device Inventory
    public void StopDev() {
        runFlag = false;
        devOpt = CMD_CLOSE;
        if (null != thInventory) {
            thInventory.interrupt();
            thInventory = null;
        }
    }

    //Set to Inventory
    public void inventory() {
        if(0==m_iModType)	//A8-A采用一发一收模式
            devOpt = CMD_INV;
        else
            reader.StartContinueInventory();
    }

    //Pause Inventory
    public void pause() {
        devOpt = CMD_PAUSE;
        reader.StopContinueInventory();
        sendMsg(MSG_INFO, "已暂停");
    }

    //Pause Inventory
    public void PauseInventory() {
        devOpt = CMD_PAUSE;
        sendMsg(MSG_PAUSE, "");
    }

    //Resume Inventory
    public void ResumeInventory() {
        devOpt = CMD_INV;
        sendMsg(MSG_RESUME,"继续");
    }

    //Hex Array --> String
    public String HexToString(byte[] bArray) {
        StringBuffer sb = new StringBuffer(bArray.length);
        String sTemp;
        for (int i = 0; i < bArray.length; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2)
                sb.append(0);
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }

    private void Sleep(int ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    // Read Card
    Runnable sendable = new Runnable() {
        @Override
        public void run() {
            //	if (!Open()) {
            //		return;
            //	}
            String szTag = "";
            while (runFlag) {
                switch (devOpt) {
                    case CMD_CLOSE:
                        runFlag = false;
                        break;
                    case CMD_INV:
                        sendMsg(MSG_INFO, "盘存中 ...");
                        List<TAGINFO> listTag = reader.Inventory(rReadTime);
                        boolean bSucc = (null != listTag);
                        Log.d("tag:Recv","read:"+ (bSucc ? "Success" : "Fail")	+ ". cnt:"+ String.valueOf(bSucc ? listTag.size() : 0));
                        if (bSucc) {
                            if (listTag.size() > 0) {
                                for (int i = 0; i < listTag.size(); i++) {
                                    TAGINFO tfs = listTag.get(i);
                                    // 处理数据
                                    szTag = HexToString(tfs.EpcId) + ";"
                                            + tfs.ReadCnt;
                                    sendMsg(MSG_EPC, szTag);
                                }
                            }
                            if (rSleepTime > 0)
                                Sleep(rSleepTime);
                        }
                        break;
                    default:// CMD_PAUSE
                        Sleep(1);
                        break;
                }
            }// while
            // Close();
            Log.d("InventoryExit", "停止盘存");
            // sendMsg(MSG_STOP, "已停止");
        }
    };
    // endregion

    //Open device
    public boolean Open() {
        Log.d("tag:Recv", "Open");
        if (devStat != DEV_STAT_CLOSE)
            return true;
        // 模块上电
        boolean bConn = reader.Connect();
        if(!bConn) {
            Sleep(1000);
            bConn = reader.Connect();
        }
        if (!bConn) {
            sendMsg(MSG_INFO, "连接失败" + reader.GetLastError());
            return false;
        }
        sendMsg(MSG_OPEN, "连接成功");
        devStat = DEV_STAT_OPEN;

        // 初始化配置
        //SetPower(30); // 设置功率30
        return true;
    }

    //open device via tcp
    public boolean OpenByTcp(String IP, int port) {
        Log.d("tag:Recv", "Open");
        if (devStat != DEV_STAT_CLOSE)
            return true;
        // 模块上电
        boolean bConn = reader.ConnectByIP(IP, port);
        if(!bConn) {
            Sleep(1000);
            bConn = reader.ConnectByIP(IP, port);
        }
        if (!bConn) {
            sendMsg(MSG_INFO, "连接失败" + reader.GetLastError());
            return false;
        }
        sendMsg(MSG_OPEN, "连接成功");
        devStat = DEV_STAT_OPEN;

        // 初始化配置
        //SetPower(30); // 设置功率30
        return true;
    }

    //disconnect to reader
    public boolean Close() {
        if (DEV_STAT_CLOSE != devStat)
            reader.Disconnect();
        devStat = DEV_STAT_CLOSE;
        Log.e("Inventory", "Close");
        return true;
    }

    // Set callback function
    public void SetHandleFunc(Handler handler) {
        msgHandler = handler;
    }

    //Set callback function
    public void SetInvCallback(InvCallBack callback) {
        reader.SetCallback(callback);
    }

    public boolean IsOpen() {
        return devStat == DEV_STAT_CLOSE ? false : true;
    }

    //update information
    public void sendMsg(int msgtype, String str) {
        if (msgHandler != null) {
            // 处理数据
            Message msg = new Message();
            msg.what = msgtype;
            Bundle bundle = new Bundle();
            bundle.putString("msg", str); // 往Bundle中存放数据
            msg.setData(bundle);// mes利用Bundle传递数据
            msgHandler.sendMessage(msg);// 用activity中的handler发送消息
        }
    }

    //set power
    public boolean SetPower(int power) {
        return reader.SetPower(power);
    }

    //query power
    public int GetPower() {
        return reader.GetPower();
    }

    //Set ReadMode: 0-省电模式(单标签读) 1-盘存模式(多标签读)
    public boolean SetReadMode(int invMode) {
        return reader.SetReadMode(invMode);
    }

    //Query Read Mode
    public int GetReadMode() {
        return reader.GetReadMode();
    }
}